import {
	getAccountRule,
	getRechargeAwards,
	recharge,
	getCategoryAvailable,
	getAccountRuleNotMember,
	updateToNewCard,
	openMemberCard,
	checkMemberCartState,
	authCheckMobile,
	checkSmsCode,
	updatePhone
} from '@src/api/member';
import {
	storeBindingsBehavior
} from 'mobx-miniprogram-bindings';
import router from '@src/router';
import member from '@src/store/member';
import base from '@src/store/base';
import $math from '@src/common/math';
import color from '@src/common/color';
import memberPayBehavior from '@src/common/memberPayBehavior';
import $cache from '@src/common/wxCache';
import chooseCardModule from '@src/pages/indexChooseCard/chooseCardModule'
import {
	parseCategoryIntro,
	parseCategoryRights,
	parsePrivileges,
	parseRechargeAwardRule,
	parseOpenCardGift
} from '@src/common/memberCardUtils';

let themeConfigMall = $cache.get('themeConfig-mall')
Component({
	behaviors: [storeBindingsBehavior, router.routerBehavior, memberPayBehavior],
	storeBindings: [{
		store: member,
		fields: ['isMember', 'categoryId', 'categoryImage', 'categoryName', 'phone', 'xhOpenId'],
		actions: ['getBaseInfo', 'syncWxCard']
	}, {
		store: base,
		fields: ['themeColor', 'themeTitleColor', 'indexPageScene']
	}],
	data: {
		accountRuleData: null,
		defaultAmountList: null,
		money: 0,
		otherInput: '',
		isPwdInit: false,

		// 轮播
		availableData: null,
		carIndex: 0,
		currentCardOrder: 2,

		curIndex: '',
		curIndexFlag: true,
		maxIndex: '',
		triggerType: '', // 区分获取奖励的方式，避免重复调用

		openCarDisable: false,

		wxCardState: {
			hasGet: false,
			hasActive: false
		},

		// 验证码
		showPopup: false, // 是否显示弹窗
		smsText: '获取验证码',
		smsCode: '',
		smsPhone: '',
		needAuth: false,
		bindType: '', //  openIdBindDifferentPhone（走获取手机验证码） phoneBindDifferentOpenId（走获取手机验证码） alreadyExists（已是会员无需开卡） directOpenCard（返回手机号直接开卡）authToGetPhone（需授权获取手机号再开卡）
		phoneCode: '',
		isPassCode: false,
		resolve: null
	},
	observers: {
		'themeColor': function (themeColor) {
			if (themeColor) {
				this.setData({
					themeColor10: color.HexToRGB(themeColor, 10)
				})
			}
		}
	},

	methods: {
		...chooseCardModule,
		onLoad({ money }) {
			this.setData({ queryMoney: money })
		},
		onLogin() {
			this.fetchData().then(res => {
             console.log(8888,res);
				setTimeout(() => {
					const { defaultAmountList: list, queryMoney } = this.data
					let item = list.filter(v => v.money === (queryMoney * 100))?.[0]
					let index = list.findIndex(v => v.money === (queryMoney * 100))
					this.handleItemClick({ currentTarget: { dataset: { index, item } } })
				}, 500)
			})
		},
		onShow() {
			this.fetchData();
		},
		onPullDownRefresh() {
			wx.stopPullDownRefresh();
			this.fetchData();
		},

		// 轮播滑动
		handleChangeIndex(e) {
			if (!this.data.isMember) {
				const index = e.detail.current;
				this.setData({
					carIndex: index
				});
				// 禁止按钮和轮播同时触发 this.fetchRechargeAwards() 有bug，暂停用; 
				// if (this.data.triggerType != 'handleItemClick') {
				// 	this.fetchRechargeAwards();
				// } else {
				// 	this.setData({
				// 		triggerType: ''
				// 	});
				// }
				this.fetchRechargeAwards();
			}
		},

		// 充值档按钮
		handleItemClick(e) {
			const item = e.currentTarget.dataset.item;
			const curIndex = e.currentTarget.dataset.index;
			let money = $math.div(item.money, 100);
			const defaultAmountList = this.data.defaultAmountList
		
			// 反选
			if (curIndex == this.data.curIndex ||money==this.data.checkMoney) {
				this.setData({
					curIndexFlag: !this.data.curIndexFlag
				})
			} else {
				this.setData({
					curIndexFlag: true
				})
			}
			if (this.data.curIndexFlag == false) {
				money = 0
			}

			this.data.passAwardData.totalMoney = ''
			this.setData({
				money,
				curIndex,
				otherInput: '',
				otherTotalMoney: '',
				triggerType: 'handleItemClick',
				openCarDisable: false
			})
			this.rechargeBanner()
			this.fetchRechargeAwards()
			// 清空充值金额
			if (!this.data.curIndexFlag) {
				this.data.money = 0
			}
		},

		// 其他金额
		handleInput(e) {
			let money = e.detail.value
			if (money.length == 1 && money[0] == '.') {
				money = '0.' // 首位 . 补0
			} else if (money.length > 1 && money[0] == 0 && money[1] != '.') {
				money = money.slice(1) // 删除首位0
			}
			money = money.match(/^\d*(\.?\d{0,2})/g)[0] || null // 限制一个小数点，两位小数
			this.setData({
				money: money,
				otherInput: money
			})

			// 置灰按钮
			if (money == 0 && this.data.curIndex == 'input') {
				this.setData({
					openCarDisable: true
				})
			} else {
				this.setData({
					openCarDisable: false
				})
			}

			const timeId = setTimeout(() => {
				clearTimeout(timeId);
				if (money && this.data.curIndex === 'input') {
					this.fetchRechargeAwards();
				} else {
					this.setData({
						money: 0
					})
				}
			}, 200);
			this.resetCurCard(this.data.availableData[this.data.carIndex])
			this.rechargeBanner()
		},
		// 焦点清空
		handleInputClean() {
			this.data.passAwardData.totalMoney = ''
			this.setData({
				money: 0,
				otherInput: '',
				curIndex: 'input',
				otherTotalMoney: '',
				passAwardData: this.data.passAwardData,
				curIndexFlag: false
			})
			this.resetCurCard(this.data.availableData[this.data.carIndex])
		},
		handleInputFocus() {
			if (this.data.curIndex != 'input') {
				this.handleInputClean()
			}
		},
		handleInputBlur() {
			if (this.data.curIndex != 'input') {
				this.handleInputClean()
			}
		},

		// 密码安全提示
		showInitPwdTips() {
			wx.showModal({
				title: '安全提示',
				content: '您正在使用会员充值，为保证账户余额安全，请务必设置支付密码配合使用！',
				confirmText: '设置密码',
				success: sm => {
					if (sm.confirm) {
						router.push({
							name: 'member/resetPassword',
							params: {
								type: 'init'
							}
						})
					}
				}
			});
		},

		// 只是充值
		rechargeFun() {
			// if (!this.data.isPwdInit) {
			//   this.showInitPwdTips();
			//   return
			// }
			if (!this.data.accountRuleData.enableOnlineRecharge) {
				wx.showModal({
					title: '余额充值提示',
					content: '自助充值功能已暂时关闭，充值请联系服务员！',
					confirmText: '好的',
					showCancel: false
				});
				return;
			}
			if (!this.data.money) {
				return;
			}

			wx.showLoading({
				title: '充值中...',
				mask: true
			});
			const data = {
				money: $math.mul(this.data.money, 100),
				payChannel: 1,
				mercNo: $cache.get('themeConfig-mall').mercNo
			};
			if (!data.money) {
				this.setData({
					isShowAward: false
				})
				return
			}
			recharge(data).then(res => {
				wx.hideLoading({
					complete() {
						setTimeout(() => {
							if (res.code !== 0) {
								wx.showToast({
									icon: 'none',
									title: res.msg
								})
							}
						}, 1000)
					}
				});

				const payData = {
					orderNo: res.data.orderCode,
					payFee: data.money,
					payChannels: ['wx'],
					hasDiscount: false
				};

				this.toMemberPay(payData).then(res => {
					// 刷新用户数据
					this.getBaseInfo();
					wx.showModal({
						title: '提示',
						content: `你的账户已成功充值${this.data.money}元${this.data.isShowAward ? '，充值应得奖励稍后自动到账，请注意查收！' : ''}`,
						cancelText: '去余额',
						confirmText: '继续充值',
						success(res) {
							if (res.confirm) { } else {
								router.redirectTo({
									name: 'balance'
								})
							}
						}
					});
				}).catch(() => { })
			}).catch((error) => {
				wx.hideLoading();
			})
		},
		// 开通会员并储值
		handleNewOpenCard() {
			if (!this.data.accountRuleData.enableOnlineRecharge) {
				wx.showModal({
					title: '余额充值提示',
					content: '自助充值功能已暂时关闭，充值请联系服务员！',
					confirmText: '好的',
					showCancel: false
				});
				return;
			}
			let resultData = {}

			if (this.data.wxCardState.hasGet && !this.data.wxCardState.hasActive) {
				resultData = this.selectComponent('#person-info').validItemArr();
				if (!resultData) {
					return;
				}
			}
			wx.showLoading({
				title: '开卡中...',
				mark: true
			});
			if (!themeConfigMall.mercNo) {
				themeConfigMall = $cache.get('themeConfig-mall')
			}
			const data = {
				categoryId: this.data.openCategoryId,
				intoWay: this.data.indexPageScene.receiveWay,
				channel: 2,
				data: resultData,
				scene: this.data.indexPageScene.scene,
				mercNo: themeConfigMall.mercNo,
				phone: this.phone || this.data.phone || null,
				money: this.data.rechargeType == 1 ? $math.mul(this.data.money, 100) : undefined
			};
			let reqApi;
			if (this.data.isMember) {
				reqApi = updateToNewCard
			} else {
				reqApi = openMemberCard
			}

			reqApi(data).then(res => {
				wx.hideLoading();
				if (res.code === 0) {
					this.setData({
						openCardData: res.data
						// bindType: ''
					})
					if (res.data.needPay) {
						const payData = {
							orderNo: res.data.orderCode,
							payChannels: ['wx'],
							hasDiscount: false
						}
						this.toMemberPay(payData).then(res => {
							this.syncStateFunc();
						}).catch(res => {
							// 解决无门槛卡，取消支付后，更新一下
							if (this.data.availableData[this.data.carIndex].category.payType ==
								1) {
								this.syncStateFunc();
							}
							console.info('支付error', res)
						});
					} else {
						this.syncStateFunc();
					}
				} else {
					wx.showToast({
						title: res.msg,
						icon: 'none',
						duration: 3000
					});
				}
				// this.handleCloseBillDetail()
			}).catch(err => {
				console.log(err)
				// wx.hideLoading();
				// this.handleCloseBillDetail()
			})
		},
		async syncStateFunc() {
			if (this.data.isPassCode) {
				const {
					bindType,
					smsCode
				} = this.data
				const miniProgram = $cache.get('miniProgram') || {}
				const extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
				const params = {
					mercNo: miniProgram.storeNo || null,
					phone: this.phone,
					type: bindType || '',
					phoneCode: smsCode,
					businessId: extConfig.businessId || null,
					xsOpenId: miniProgram.xsOpenId || null
				}
				const themeConfigMall = $cache.get('themeConfig-mall') || {}
				checkSmsCode({
					data: params,
					header: {
						xhOpenId: this.data.xhOpenId || null,
						mercNo: themeConfigMall.mercNo
					}
				})
					.then(res => {
						this.setData({
							bindType: ''
						})
					})

			}
			// 刷新会员数据
			// this.syncWxCard();
			wx.showToast({
				title: '操作成功',
				success: () => {
					setTimeout(() => {
						wx.navigateBack()
					}, 1500)
				}
			})
			this.getBaseInfo();
		},

		// 获取手机号
		getPhoneNumber(e) {
			// if (!this.data.login) {
			// 	const loginComp = this.selectComponent("#login");
			// 	loginComp.requireLogin();
			// 	return;
			// }
			if (this.data.money < this.data.accountRuleData.minAmount / 100 && this.data.curIndex == 'input' &&
				this.data.otherInput != '') {
				wx.showToast({
					title: '低于最低充值限额',
					icon: 'none',
					duration: 1500
				});
				return
			}
			if (!e.detail.iv) {
				wx.showToast({
					title: '手机号获取失败，请重试',
					icon: 'none',
					duration: 1500
				});
				return;
			}
			const reqData = {
				ivStr: e.detail.iv,
				encryptedData: e.detail.encryptedData
			}

			checkMemberCartState(reqData).then(res => {
				const themeConfigMall = $cache.get('themeConfig-mall')
				this.phone = res.data.phone
				authCheckMobile({
					data: {
						phone: res.data.phone
					},
					header: {
						xhOpenId: this.data.xhOpenId || null,
						mercNo: themeConfigMall.mercNo
					}
				}).then(result => {
					if (result.code === 0 && result.data
						.type) { // result.data.type   (同一个手机号绑定了两个openId)
						return this.setData({
							bindType: result.data.type,
							showPopup: true,
							member: result.data.member,
							smsPhone: res.data.phone ? this.filterMobile(res.data
								.phone) : ''
						}, () => {
							if (result.data.type === 'openIdBindDifferentPhone' ||
								result.data.type === 'phoneBindDifferentOpenId') {
								this.handleSmsCode()
							}
						})
					} else {
						if (res.data.mergeCustomer) {
							// 重新设置token
							const expireTime = $cache.ttl('token');
							$cache.setSync('token', res.data.newToken, expireTime);
							wx.showModal({
								title: '您已经是会员~',
								content: '返回首页',
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										router.redirectTo({
											name: 'index'
										})
									}
								}
							});
						} else if (res.data.isOfflineMember) {
							router.push({
								name: 'member/bindOldMemberConfirm',
								success: routerRes => {
									routerRes.eventChannel.emit(
										'oldMemberData', {
										'ivStr': reqData.ivStr,
										'encryptedData': reqData
											.encryptedData,
										'oldMemberInfo': res.data
									})
								}
							})
						} else {
							// 这个判断导致付费卡要授权2次,原因未知
							// todo 这里是新逻辑
							// if (!this.data.category.firstYearFree && !this.data.billDetailModal) {
							//   this.setData({
							//     billDetailModal: true
							//   })
							// } else {
							//   this.handleNewOpenCard()
							// }
							// 是会员，手机号空情况下
							if (this.data.isMember) {
								let data = {
									ivStr: reqData.ivStr,
									encryptedData: reqData.encryptedData,
								}
								updatePhone(data).then(res => {
									console.log('是会员，手机号空情况下', res)
									this.rechargeFun()
								})
							} else {
								this.handleNewOpenCard()
							}

							// 跳一键激活页面
							// router.push({
							//   name: "member/activeMemberCard",
							//   params: {
							//     categoryId: this.data.category.id
							//   }
							// })
						}
					}
				})
			})
		},
		close() {
			this.phone = null
			this.setData({
				showPopup: false,
				bindType: null
			})
		},

		// 充值/开卡按钮
		handleConfirm() {
			if (this.data.money < this.data.accountRuleData.minAmount / 100 && this.data.curIndex == 'input' &&
				this.data.otherInput != '') {
				wx.showToast({
					title: '低于最低充值限额',
					icon: 'none',
					duration: 1500
				});
				return
			}

			// console.log('开通类型-- 0只是充值 1开通会员并储值 2仅开通会员', this.data.rechargeType)
			const rechargeType = this.data.rechargeType
			if (rechargeType == 0) {
				this.rechargeFun()
			} else if (rechargeType == 1) {
				this.handleNewOpenCard()
			} else {
				this.handleNewOpenCard()
			}
		},

		// 获取充值奖励
		fetchRechargeAwards() {
			const data = {
				money: $math.mul(this.data.money, 100)
			};
			if (!data.money) {
				this.setData({
					isShowAward: false
				})
			}

			if (this.data.isMember) {
				this.getMemberAwardsFun(data)
			} else {
				this.getNotMemberAwardsFun()
			}
		},
		// 会员充值奖励
		getMemberAwardsFun(data) {
			getRechargeAwards(data).then(res => {
				if (res.code === 0) {
					// 请求成功
					const resData = res.data;
					const passAwardData = resData;
					const rechargeAward = resData.rechargeAward;
					rechargeAward.balance = $math.div(rechargeAward.balance, 100);
					const queryAwardData = rechargeAward;
					const awardCoupon = rechargeAward.coupons;
					const isShowAward = passAwardData.newCategory || queryAwardData.balance / 100 ||
						queryAwardData.points || awardCoupon.length
					this.setData({
						passAwardData,
						queryAwardData,
						awardCoupon,
						isShowAward
					})
				}
				this.data.resolve()
			})
		},
		// 非会员充值奖励
		getNotMemberAwardsFun() {
			const that = this
			const availableData = this.data.availableData
			const carIndex = this.data.carIndex
			const curIndexFlag = this.data.curIndexFlag
			let params = ''
			if (curIndexFlag) {
				params = {
					categoryId: availableData[carIndex].category.id,
					money: $math.mul(this.data.money, 100)
				}
			} else {
				params = {
					categoryId: availableData[carIndex].category.id,
					otherMoney: $math.mul(this.data.money, 100)
				}
			}
			getAccountRuleNotMember(params).then(res => {
				const that = this
				if (res.code === 0) {
					// 请求成功
					const resData = res.data;
					const passAwardData = resData;
					const rechargeAward = resData.rechargeAward;
					const accountRuleData = res.data;
					const defaultAmountList = resData.defaultAmounts;
					rechargeAward.balance = $math.div(rechargeAward.balance, 100);
					const queryAwardData = rechargeAward;
					const awardCoupon = rechargeAward.coupons;
					const isShowAward = passAwardData.newCategory || queryAwardData.balance / 100 ||
						queryAwardData.points || awardCoupon.length
					this.setData({
						passAwardData,
						queryAwardData,
						awardCoupon,
						isShowAward,
						accountRuleData,
						defaultAmountList
					})
					that.disableRecharFun()
				}
			})
		},

		// 充值档对应的轮播
		rechargeBanner() {
			const curIndex = this.data.curIndex
			const carIndex = this.data.carIndex
			const availableData = this.data.availableData
			// 选中充值金额
			if (!isNaN(curIndex)) {
				const defaultAmountList = this.data.defaultAmountList
				const newCategoryId = defaultAmountList[curIndex].newCategoryId
				if (newCategoryId) {
					availableData.forEach((el, index) => {
						if (newCategoryId == el.category.id) {
							this.setData({
								carIndex: index
							})
						}
					})
				}
			} else {
				// 其他金额
				const curIndexFlag = this.data.curIndexFlag
				let params = ''
				if (curIndexFlag) {
					params = {
						categoryId: availableData[carIndex].category.id,
						money: $math.mul(this.data.money, 100)
					}
				} else {
					params = {
						categoryId: availableData[carIndex].category.id,
						otherMoney: $math.mul(this.data.money, 100)
					}
				}
				getAccountRuleNotMember(params).then(res => {
					if (res.code === 0) {
						const selectedCategoryId = res.data.selectedCategoryId
						const otherTotalMoney = res.data.otherTotalMoney
						this.setData({
							otherTotalMoney
						})
						if (selectedCategoryId) {
							availableData.forEach((el, index) => {
								if (selectedCategoryId == el.category.id) {
									this.setData({
										carIndex: index
									})
								}
							})
						}
					}
				})
			}
		},

		// 设置默认金额
		setDefaultMoneyFun() {
			const availableData = this.data.availableData
			const carIndex = this.data.carIndex
			if (this.data.isMember) {
				getAccountRule().then(res => {
					if (res.code === 0) {
						// 请求成功
						const accountRuleData = res.data;
						const defaultAmountList = res.data.defaultAmounts;
						this.setData({
							accountRuleData,
							defaultAmountList
						})
						// 设置金额默认值
						if (!this.data.curIndex && defaultAmountList) {
							const money = $math.div(defaultAmountList[0].money, 100);
							this.setData({
								money,
								curIndex: 0
							})
						}
						this.rechargeBanner()
					}
				})
			} else {
				const curIndexFlag = this.data.curIndexFlag
				let params = ''
				if (curIndexFlag) {
					params = {
						categoryId: availableData[carIndex].category.id,
						money: $math.mul(this.data.money, 100)
					}
				} else {
					params = {
						categoryId: availableData[carIndex].category.id,
						otherMoney: $math.mul(this.data.money, 100)
					}
				}
				getAccountRuleNotMember(params).then(res => {
					if (res.code === 0) {
						// 请求成功
						const accountRuleData = res.data;
						const defaultAmountList = res.data.defaultAmounts;
						this.setData({
							accountRuleData,
							defaultAmountList
						})
						// 设置金额默认值
						if (!this.data.curIndex && defaultAmountList) {
							const money = $math.div(defaultAmountList[0].money, 100);
							this.setData({
								money,
								curIndex: 0
							})
							this.resetCurCard(availableData[0]);
						}
						this.rechargeBanner()
					}
				})
			}
		},

		// 初始化
		fetchData() {
			return new Promise((resolve, reject) => {
				// 获取轮播
				getCategoryAvailable().then(res => {
					if (res.code === 0) {
						const availableData = res.data
						this.setData({
							'availableData': availableData,
							resolve
						})
						if (availableData && availableData.length > 0) {
							if (this.data.enterCategoryId) {
								const items = availableData.filter(item => item.category.id === this.data
									.enterCategoryId)
								for (let i = 0; i < availableData.length; i++) {
									const item = availableData[i];
									if (item.category.id === this.data.enterCategoryId) {
										this.setData({
											enterCategoryId: null,
											carIndex: i
										});
										this.resetCurCard(items[0]);
										return;
									}
								}
							}

							// 会员走这里
							if (this.data.isMember) {
								for (let i = 0; i < availableData.length; i++) {
									if (this.data.categoryId == availableData[i].category.id) {
										this.setData({
											carIndex: i
										});
										this.resetCurCard(availableData[i]);
									}
								}
							}

							if (this.data.carIndex && this.data.carIndex < availableData.length) {
								this.resetCurCard(availableData[this.data.carIndex]);
							} else {
								this.setData({
									carIndex: 0
								})
								this.resetCurCard(availableData[0]);
							}
						}
						this.setDefaultMoneyFun()
						this.fetchRechargeAwards();
						resolve()
					}
				})
			})
		},

		// 设置会员卡信息（2）
		setCard(card) {
			const category = card.category;
			const isMember = this.data.isMember // 是否会员
			const categoryId = this.data.categoryId // 当前等级id
			const curIndexFlag = this.data.curIndexFlag // 是否选中
			const money = this.data.money
			let openDesTitle = '' // 开通费用描述
			let openCardBtnTitle = '立即开通'
			let rechargeType = '' // 充值类型  0只是充值 1开通会员并储值 2仅开通会员

			if (isMember) {
				openCardBtnTitle = '确认充值';
				if (money) {
					openDesTitle = `充值${money}元`
				} else {
					openDesTitle = ''
				}
				rechargeType = 0
			} else {
				if (money) {
					openCardBtnTitle = '开通会员并储值';
					if (category.payType === 1) {
						openDesTitle = `充值${money}元`
					} else if (category.payType === 2) {
						openDesTitle = `充值${money}元 + 开卡费${category.payCost / 100}元`
						if (!category.firstYearFree) {
							openDesTitle = `充值${money}元 + 开卡费${(category.payCost + category.annualFee) / 100}元`
						}
					} else if (category.payType === 3) {
						openDesTitle = `充值${money}元`
					}
					rechargeType = 1
				} else {
					if (category.payType === 1) {
						openCardBtnTitle = '立即开卡';
					} else if (category.payType === 2) {
						openCardBtnTitle = `付费${category.payCost / 100}元开通`;
						if (!category.firstYearFree) {
							openCardBtnTitle = `付费${(category.payCost + category.annualFee) / 100}元开通`;
						}
					} else if (category.payType === 3) {
						openCardBtnTitle = `预存${category.rechargeCost / 100}元开通`;
					}
					rechargeType = 2
				}
			}

			this.setData({
				openCardBtnTitle,
				openDesTitle,
				rechargeType,
				category
				// openCategoryId: this.data.category.id
			})
		},

		// 设置会员卡信息（1）
		resetCurCard(card) {
			const category = card.category;
			let privileges = card.privileges;
			const rechargeAward = card.rechargeAward;
			const introList = parseCategoryIntro(category);
			const categoryRights = parseCategoryRights(category, rechargeAward).concat(parseRechargeAwardRule(
				rechargeAward));
			let validPeriod = category.validPeriod + '年';
			if (category.validPeriod == 0) {
				validPeriod = '永久'
			}
			privileges = parsePrivileges(privileges);
			const openCardGift = parseOpenCardGift(category, card.openCardCouponAward, true);
			const currentCardOrder = category.cardOrder;

			// if (category.payType === 1) {
			//   openCardBtnTitle = "立即开卡";
			// } else if (category.payType === 2) {
			//   openCardBtnTitle = `付费${category.payCost / 100}元开通`;
			//   if (!category.firstYearFree) {
			//     openCardBtnTitle = `付费${(category.payCost + category.annualFee) / 100}元开通`;
			//   }
			// } else if (category.payType === 3) {
			//   openCardBtnTitle = `预存${category.rechargeCost / 100}元开通`;
			// }
			this.setCard(card)

			if (categoryRights.length > 0) {
				categoryRights.forEach(item => {
					if (item.iconName) {
						if (item.iconName.substr(0, 4) == 'icon') {
							item.icon = true
						} else {
							item.icon = false
						}
					}
				})
			}
			let customOpenRewards = [];
			if (category.customGift) {
				customOpenRewards = JSON.parse(category.customGift)
			}
			if (category.instructions) {
				introList.push(category.instructions)
			}

			this.setData({
				category,
				categoryRights,
				introList,
				privileges,
				rechargeAward,
				validPeriod,
				openCardGift,
				currentCardOrder,
				customOpenRewards
			})
			this.setData({
				openCategoryId: this.data.category.id
			})
		},

		// 置灰充值选项
		async disableRecharFun() {
			const card = this.data.availableData[this.data.carIndex]
			if (!this.data.isMember) {
				const {
					rechargeCost
				} = card.category
				const defaultAmountList = this.data.defaultAmountList
				if (defaultAmountList) {
					const maxIndexArr = []
					defaultAmountList.forEach((el, index) => {
						const money = el.money
						if (money < rechargeCost) {
							maxIndexArr.push(index)
							defaultAmountList[index].disable = true
						} else {
							defaultAmountList[index].disable = false
						}
					})
					this.setData({
						defaultAmountList,
					})

					// 处理点击索引
					const maxIndex = Math.max.apply(null, maxIndexArr)
					if (this.data.curIndex <= maxIndex) {
						this.setData({
							curIndex: null,
							money: 0
						})
					}
					if (maxIndex < this.data.maxIndex) {
						this.setData({
							curIndex: null,
							money: 0
						})
					}

					// 处理点击“可升级充值档”，再切换轮播为“不可升级充值档”，取消选中
					let rechargeCategoryId = card.category.id
					if (rechargeCategoryId < this.data.rechargeCategoryId) {
						if (maxIndex == '-Infinity' && this.data.maxIndex == '-Infinity') {
							this.setData({
								curIndex: null,
								money: 0
							})
						}
					}
					this.setData({
						maxIndex,
						rechargeCategoryId
					})
				}
				this.resetCurCard(card)
			}
		},

		// 分享
		onShareAppMessage() {
			const homePageConfig = this.data.homePage.config;
			const data = {
				path: `sp-member/pages/balanceRecharge/main`
			}
			if (homePageConfig.shareTitle) {
				data['title'] = homePageConfig.shareTitle;
			} else {
				data['title'] = this.data.businessName;
			}
			if (homePageConfig.shareImageUrl) {
				data['imageUrl'] = homePageConfig.shareImageUrl;
			}
			return data;
		}
	}
})
